package icu.wangrui.bookstore.controller;

import icu.wangrui.bookstore.dto.QQUser;
import icu.wangrui.bookstore.pojo.User;
import icu.wangrui.bookstore.provider.QQProvider;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@Controller
@Slf4j
@Data
public class AuthorizeController {
    @Autowired
    private QQProvider qqProvider;


    //QQ回调地址
    @GetMapping("/callbackQQ")
    public String callbackQQ(@RequestParam(name="code")String code,
                             @RequestParam(name="state")String state,
                             HttpServletResponse response,
                             HttpSession httpSession,
                             Model model){
        String accessToken = qqProvider.getAccessToken(code);
        String openId = qqProvider.getOpenId(accessToken);
        QQUser qqUser = qqProvider.getQQUser(accessToken, openId);


        if (qqUser != null && qqUser.getRet() == 0) {
            //String token = UUID.randomUUID().toString();
            //setUserInfo(token, qqUser.getNickname(), qqUser.getAvatarUrl(), "QQ-"+openId);
            //addCookieForToken(response, token);
            //返回首页
            String nickname = qqUser.getNickname();
            String figureurl_qq_2 = qqUser.getFigureurl_qq_2();
            httpSession.setAttribute("nickname",nickname);
            httpSession.setAttribute("figureurl_qq_2",figureurl_qq_2);
            return "redirect:/user/page/index";
        } else {
            log.error("QQ callback get error");
            //登录失败
            return "redirect:/userlogin.html";
        }

    }

    //将token添加到cookie
    private void addCookieForToken(HttpServletResponse response, String token) {
        Cookie cookie = new Cookie("token", token);
        cookie.setMaxAge(60 * 60 * 24 * 7);//7天有效期
        response.addCookie(cookie);
    }

    //设置用户信息
    private void setUserInfo(String token, String name, String avatarUrl,String accountId){

    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request,
                         HttpServletResponse response){
        request.getSession().removeAttribute("user");
        Cookie cookie = new Cookie("token", null);
        cookie.setMaxAge(0);//立马失效
        response.addCookie(cookie);
        return "redirect:/";
    }
}
